var express = require('express');
var router = express.Router();
//导入 shortid
const AccountModel = require('../../models/AccountModel')
const moment = require("moment");



//导入检测成功的中间件
//声明中间件检测登录
const checkLogin = require('../../middleWare/checkLogin')


router.get('/', (req, res) => {
  res.redirect('/account')
})



//记账本的列表
router.get('/account',checkLogin, function(req, res, next) {
 //判断是否登录



  //获取所有的账单信息
  AccountModel.find().sort({time:-1}).then((data) => {
    res.render('list',{accounts:data})
  })
});

//添加记录
router.get('/account/create', checkLogin,function(req, res, next) {
  res.render('create');
});

//新增记录
router.post('/account',checkLogin, (req, res) => {
  AccountModel.create(
    {
      ...req.body,
      time:moment(req.body.time).toDate()
    }
  )
    .then(() => {
      res.render('success',{msg:'成功添加',url:'/account'})
    })
    .catch((err) => {
      res.status(500)
    })

});
router.get('/account/:id',checkLogin,(req, res) => {
  let id = req.params.id
  AccountModel.deleteOne({_id:id}).then(()=>{
    res.render('success',{msg:'成功删除',url:'/account'})
    console.log('删除成功')})
})


module.exports = router;
